package cn.itcast.bos.web.action.take_delivery;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.utils.UUIDUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: SOS
 * @create: 2018-02-26 11:38
 */

@ParentPackage("json-default")
@Namespace("/")
@Controller()
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion>{

    @Autowired
    private PromotionService promotionService;

    //属性驱动接受文件上传
    private File titleImgFile;
    private String titleImgFileFileName;

    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }

    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }

    @Action(value = "promotion_save",results = {@Result(name = SUCCESS,location = "./pages/take_delivery/promotion.html",type = "redirect"),
            @Result(name = "input",location = "./index.html",type = "redirect")})
    public String promotionSave() throws IOException {

        //接受文件上传
        //保存文件的地址
        String savePath = ServletActionContext.getServletContext().getRealPath("/upload");

        //访问的url
        String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload";

        String uuid = UUIDUtils.getUUID();

        //拼接文件,获得文件的扩展名
        String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));

        String randomFileName = uuid + ext;

        //复制文件
        FileUtils.copyFile(titleImgFile,new File(savePath,randomFileName));

        //保存图片的访问地址
        model.setTitleImg(saveUrl+"/"+randomFileName);
        System.out.println(saveUrl);
        //调用业务层保存
        promotionService.save(model);


        return SUCCESS;
    }

    @Action(value = "promotion_page",results = {@Result(name = SUCCESS,type = "json"),
            @Result(name = "input",location = "./index.html",type = "redirect")})
    public String pageQuery(){
        //构造分页查询
        Pageable pageable = new PageRequest(page-1,rows);

        Page<Promotion> pageDate =  promotionService.findPageDate(pageable);
        pushPageDataToValueStack(pageDate);
        return SUCCESS;
    }
}
